#!/usr/bin/python
#encoding=utf-8

'''
Created on May 16, 2014

@author: root
'''
import os
import uuid
import urllib
import time
from wm.etc.config import DIRS,CLUSTER,ALARMTYPE,SOCKET
from wm.db.TransactionManager import TransactionManager
from wm.lib import monitorlib,wmalert
from wm.lib.tam.htmlparser import Parser
from wm.lib.tam.detection import compare_file
from wm.lib.tam.swf import swf_malurl_check

def download_file_content(_eurl,_file_path):
    try:
        suffix = ''
        index = _eurl.rfind(".")
        if index != -1:
            suffix = _eurl[index+1:len(_eurl)]
            fname = _file_path + uuid.uuid1().__str__().replace("-","") + "." + suffix
            webpage = urllib.urlopen(_eurl)
            fd = open(fname,'wb')
            fd.write(webpage.read())
            fd.close()
            return fname
    except Exception as e:
        print 'get url content error',str(e)
        raise
    return ''

class Tamper(object):
    
    def __init__(self,tamper_path = DIRS['TAMPER_PATH'],
                 tamper_tmp_path = DIRS['TAMPER_TMP_PATH']):
        self.tamper_path = tamper_path
        self.tamper_tmp_path = tamper_tmp_path
        
        try:
            if not os.path.exists(tamper_path):
                os.system('mkdir -p ' + tamper_path)
                self.tamper_path = tamper_path
                
            if not os.path.exists(tamper_tmp_path):
                os.system('mkdir -p ' + tamper_tmp_path)
                self.tamper_tmp_path = tamper_tmp_path
        except:
            print 'failed to create tamper path '
        
        self.init_tamper_task()
        
        
    def init_tamper_task(self):
        '''
        '''
        tran = TransactionManager()
        try:
            sql = "select pa.id,pa.uRLType,pa.elementURL,pa.local from pageanalyzer as pa,websiteconfiginfo as wc where pa.websiteConfigInfo_id = wc.id and wc.cluster="+str(CLUSTER['cluster'])
            palist = tran.select(sql) 
            if palist:
                for pa in palist:
                    if pa[3] is None or not os.path.exists(pa[3]):
                        try:
                            fpath = download_file_content(pa[2],self.tamper_path) 
                        except Exception as e:
                            time.sleep(SOCKET['INTERVAL'])
                            continue
                        sql = "update pageanalyzer set local='"+fpath+"',modifyDate=CURRENT_TIMESTAMP() where id='" +pa[0]+"'"   
                        print sql
                        tran.update(sql)               
            tran.commitTransaction()   
        except:
            tran.rollbackTransaction()
        finally:
            tran.close()
    
    def get_alarm_content(self,site_name,url_type,eurl):
        if url_type == 0:
            return site_name+'图片被篡改,地址：'+eurl
        elif url_type == 1:
            return site_name+'flash文件被篡改（有可能包含恶意代码）,地址：'+eurl
   
    def check_tamper(self,pa):
        is_tamper = False 
        tran = TransactionManager()
        try:
            fpath = download_file_content(pa[2],self.tamper_tmp_path)  
            is_tamper = compare_file(pa[3],fpath)
            print '----------------%s',is_tamper
            is_mal,url = swf_malurl_check(fpath)
            #is_tamper = True
            if is_tamper or is_mal:
                alarmcontent = self.get_alarm_content(pa[4],pa[1],pa[2])
                print '-----%s---------'%(alarmcontent,)
                alarmid = uuid.uuid1().__str__().replace("-","") 
                sql = "insert into alarmevent(id,createDate,modifyDate,alertCategory,alertContent,occurrenceDate,status,websiteName,websiteConfigInfo_id) "+\
                                            "values('" + alarmid + "'," + " CURRENT_TIMESTAMP()," + " CURRENT_TIMESTAMP()," +\
                                            str(ALARMTYPE['PAGE_TAMPER_ALARM']) + ",'"+ alarmcontent + "'," + "CURRENT_TIMESTAMP()," + str(0) + ",'" + pa[4] + "','"+ pa[5] + "')"
                tran.execute(sql)
                sql = "insert into pagetamper(id,createDate,modifyDate,isTampered,tamperContent,websiteConfigInfo_id,alarmEvent_id) values(replace(uuid(),'-',''),CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP(),1,'"+alarmcontent+"','"+pa[5]+"','"+alarmid+"')"
                tran.execute(sql)
                            
                monitorlib.update_recent_alarmevent(tran,pa[5],pa[4],str(ALARMTYPE['PAGE_TAMPER_ALARM']),alarmcontent)
                wmalert.website_alert(alarm_type=ALARMTYPE['PAGE_TAMPER_ALARM'],websiteid=pa[5],websitename=pa[4],url=pa[2],content=alarmcontent)  
            
            tran.commitTransaction()
        except:
            tran.rollbackTransaction()
        finally:
            tran.close()
                   
    def get_detection_result(self):
        is_tamper = False
        tran = TransactionManager()
        try:
            sql = "select pa.id,pa.uRLType,pa.elementURL,pa.local,wc.websitename,pa.websiteConfigInfo_id  from pageanalyzer as pa,websiteconfiginfo as wc where pa.websiteConfigInfo_id = wc.id and wc.cluster="+str(CLUSTER['cluster'])
            palist = tran.select(sql) 
            if palist:
                for pa in palist:
                    try:
                        parser = Parser(self.tamper_tmp_path,pa[2])
                        fpath = parser.download_file_content()      
                    except:
                        continue                    
                    is_tamper = compare_file(pa[3],fpath)
                    print '------------',is_tamper 
                    
                    #is_mal,url = swf_malurl_check(fpath)
                    is_tamper = True
                    if is_tamper:
                        alarmcontent = self.get_alarm_content(pa[4],pa[1],pa[2])
                        '''
                        alarmid = uuid.uuid1().__str__().replace("-","") 
                        sql = "insert into alarmevent(id,createDate,modifyDate,alertCategory,alertContent,occurrenceDate,status,websiteName,websiteConfigInfo_id) "+\
                                        "values('" + alarmid + "'," + " CURRENT_TIMESTAMP()," + " CURRENT_TIMESTAMP()," +\
                                        str(ALARMTYPE['PAGE_TAMPER_ALARM']) + ",'"+ alarmcontent + "'," + "CURRENT_TIMESTAMP()," + str(0) + ",'" + pa[4] + "','"+ pa[5] + "')"
                        tran.execute(sql)
                        sql = "insert into pagetamper(id,createDate,modifyDate,isTampered,tamperContent,websiteConfigInfo_id,alarmEvent_id) values(replace(uuid(),'-',''),CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP(),1,'"+alarmcontent+"','"+pa[5]+"','"+alarmid+"')"
                        tran.execute(sql)
                        
                        monitorlib.update_recent_alarmevent(tran,pa[5],pa[4],str(ALARMTYPE['PAGE_TAMPER_ALARM']),alarmcontent)
                        '''
                        wmalert.website_alert(alarm_type=ALARMTYPE['PAGE_TAMPER_ALARM'],websiteid=pa[5],websitename=pa[4],url=pa[2],content=alarmcontent)            
        
            tran.commitTransaction()
        except:
            tran.rollbackTransaction()
        finally:
            tran.close()
        
       
        return is_tamper
    
def main():
    t = Tamper()
    print t.get_detection_result()

#tam = Tamper()
    
if __name__ == '__main__':
    print '----------starting------------------'
    #main()
    
    